import { setToken, getToken, removeToken } from '@/utils/auth'
import { login, getUserInfo, getUserDetailById } from '@/api/user'
import router from '@/router'

const state = {
  // token: localStorage.getItem('token') || ''
  // cookies存储token
  token: getToken() || '',
  // 用户资料
  userInfo: {},
  // 公司id
  companyId: ''
}
const mutations = {
  // 存储token
  setToken(state, data) {
    // localStorage.setItem('token', data)
    setToken(data)
    state.token = data
  },
  // 存储用户资料
  setUserInfo(state, data) {
    state.userInfo = { ...data }
  },
  // 删除token
  removeToken(state) {
    removeToken()
    state.token = ''
  },
  // 删除用户资料
  removeUserInfo(state) {
    state.userInfo = {}
  }

}
const actions = {
  // 登录
  async login(store, data) {
    // 发请求，拿到返回值
    const res = await login(data)
    // 调用方法存储token
    store.commit('setToken', res)
  },

  // 用户资料
  async getUserInfo(store) {
    // 发请求拿到用户资料数据
    const res = await getUserInfo()
    // 拿到用户头像数据
    const result = await getUserDetailById(res.userId)
    // 存储公司id
    store.state.companyId = result.companyId
    // 合并数据
    const userinfo = { ...res, ...result }
    // console.log(userinfo)
    store.commit('setUserInfo', userinfo)
  },
  // 退出删除用户资料和token
  async delUserInfo(store) {
    await store.commit('removeToken')
    await store.commit('removeUserInfo')
    router.push('/login')
  }
}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}

